<template>
  <div class="table">
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-menu"></i>{{$route.name}}
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="handle-box">
      <el-dialog
        :title="title"
        :visible.sync="dialogFormVisible"
      >
        <el-form
          :model="addForm"
          :rules="rules"
        >
          <el-form-item
            label="广告类型"
            :label-width="formLabelWidth"
          >
            <el-select
              v-model="addForm.type"
              placeholder="请选择广告类型"
            >
              <el-option
                v-for="(item,index) in adtypes"
                :key="item.value"
                :label="item.title"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="this.addForm.type==2"
            label="专题广告类型"
            :label-width="formLabelWidth"
          >
            <el-select
              v-model="addForm.theme_ad_id"
              placeholder="请选择专题广告类型"
            >
              <el-option
                v-for="(item,index) in themeAdTypes"
                :key="item.name"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="广告位"
            prop="position"
            :label-width="formLabelWidth"
          >
            <el-select
              v-model="addForm.position"
              placeholder="请选择广告位"
            >
              <el-option
                v-for="(item,index) in types"
                :key="item.title"
                :label="item.title"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="内容"
            :label-width="formLabelWidth"
          >
            <el-input
              type="textarea"
              v-model="addForm.content"
              auto-complete="off"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="图片"
            :label-width="formLabelWidth"
            prop="img"
          >
            <el-upload
              class="avatar-uploader"
              ref="upload"
              action=""
              :http-request="uploadRequest"
              :show-file-list="false"
              v-loading.fullscreen.lock="fullscreenLoading"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="imageUrl"
                :src="imageUrl"
                class="avatar"
              >
              <i
                v-else
                class="el-icon-plus avatar-uploader-icon"
              ></i>
            </el-upload>
          </el-form-item>

        </el-form>
        <div
          slot="footer"
          class="dialog-footer"
        >
          <el-button @click="cancel(addForm)">取 消</el-button>
          <el-button
            type="primary"
            @click="add"
          >确 定</el-button>
        </div>
      </el-dialog>
      <el-input
        v-model="searchKey"
        placeholder="输入关键字"
        @click="search"
        class="search"
      ></el-input>
      <el-button
        type="primary"
        icon="search"
        @click="search"
      >搜索</el-button>
      <el-button
        type="primary"
        @click="addEx"
      >新增广告</el-button>
    </div>
    <div>
      <el-table
        :data="pics"
        border
        fit
        style="width: 100%"
      >
        <el-table-column label="图片">
          <template slot-scope="scope">
            <img
              :src="scope.row.img"
              width="100%"
              height="100%"
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="create_at"
          label="添加时间"
          :formatter="timeFormatter"
        >
        </el-table-column>
        <el-table-column
          prop="state"
          :formatter="formatStatus"
          label="状态"
        >
        </el-table-column>
        <el-table-column
          prop="position"
          label="广告位"
          :formatter="positionFormatter"
        >
        </el-table-column>
        <el-table-column
          prop="type"
          label="广告类型"
          :formatter="typeFormatter"
        >
        </el-table-column>
        <el-table-column
          prop="parentName"
          label="专题广告类型"
        >
        </el-table-column
          <el-table-column
          label="内容"
          prop="content"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          prop="state"
          label="状态"
          show-overflow-tooltip
          empty-text
          :formatter="stateFormatter"
        >
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="editPic(scope.row)"
              size="small"
            >编辑</el-button>
            <el-button
              type="text"
              @click="delPic(scope.row)"
              size="small"
            >删除</el-button>
            <el-switch
              v-model="scope.row.state === 1 ? true : false"
              active-color="#13ce66"
              @change="switchChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="block">
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page="page.number"
        layout="total, prev, pager, next, jumper"
        :total="page.total"
      >
      </el-pagination>
    </div>
  </div>
</template>
<script>
import { ad, uploadFile, getParentAdTypes } from '../../server/getDate.js'
import { mapState, mapActions } from 'vuex'
import { location, dateFormatter, filterObj } from '../../utils/local.js'
const { listApi, addApi, deleteApi, updateApi, disableApi } = ad
export default {
  data() {
    return {
      addForm: {},
      dialogFormVisible: false,
      title: '',
      imageUrl: '',
      formLabelWidth: '120px',
      show: false,
      fullscreenLoading: false,
      adtypes: [{
        title: '图片广告',
        value: 1
      }, {
        title: '专题广告',
        value: 2
      }],
      searchKey: '',
      types: [{
        title: '头部',
        value: '0'
      }, {
        title: '上左',
        value: '1-1'
      }, {
        title: '上中',
        value: '1-2'
      }, {
        title: '上右',
        value: '1-3'
      }, {
        title: '中左',
        value: '2-1'
      }, {
        title: '中中',
        value: '2-2'
      }, {
        title: '中右',
        value: '2-3'
      }, {
        title: '中下左',
        value: '2-4'
      }, {
        title: '中下右',
        value: '2-5'
      }, {
        title: '下',
        value: '3'
      }],
      rules: {
        position: [{ required: true, message: '请选择图片位置', trigger: 'blur' }],
        img: [{ required: true, message: '请上传图片', trigger: 'blur' }]
      },
    }
  },
  created() {
    this.getIndexPic(1)
    this.allThemeAdType()
  },
  computed: {
    ...mapState({
      pics: state => state.Ad.pics,
      page: state => state.Ad.picPage,
      themeAdTypes: state => state.ThemeAd.adTypeList
    })
  },
  methods: {
    ...mapActions(['savePicList', 'saveParentAdTypes']),
    allThemeAdType() {
      const params = {
        page: 1,
        pageSize: 100
      }
      getParentAdTypes({ ...params }).then(res => {
        if (res.code === '000000') {
          this.saveParentAdTypes(res
          )
        } else {
          this.$message.error(res.message)
        }
      }, err => this.$message.error(err.message))
    },
    getIndexPic(number) {
      const parmas = {
        page: number,
        pageSize: 10
      }
      if (this.searchKey !== '') {
        parmas.searchKey = this.searchKey
      }
      listApi({ ...parmas }).then(res => {
        if (res.code === '000000') {
          this.savePicList({
            ...res,
            number
          })
        } else {
          this.$message.error(res.message)
        }
      }, err => this.$message.error('服务器异常'))
    },
    timeFormatter(row) {
      return dateFormatter(row.create_at) || ''
    },
    stateFormatter(row) {
      return row.state === 1 ? '展示' : '不展示'
    },
    // themetypeFormatter(row) {
    //   return row.theme_ad_id ? this.themeAdTypes.find(item => item.id == row.theme_ad_id).name : ''
    // },
    search() {
      this.getIndexPic(this.page.number)
    },
    add() {
      if (!this.addForm.position) {
        this.$message.warning('请选择图片位置')
        return
      }
      if (!this.imageUrl) {
        this.$message.warning('请上传图片')
        return
      }
      this.addForm.img = this.imageUrl
      if(this.addForm.type==1){
          this.addForm.theme_ad_id =0
      }
      if (this.addForm.id) {
        updateApi({ ...this.addForm })
          .then(res => {
            if (res.code === '000000') {
              this.dialogFormVisible = false
              this.$message.success('修改成功')
              this.getIndexPic(this.page.number)
            } else {
              this.$message.error(res.message)
            }
          }, err => this.$message.error('服务器异常'))
      } else {
        addApi({ ...this.addForm })
          .then(res => {
            if (res.code === '000000') {
              this.dialogFormVisible = false
              this.getIndexPic(this.page.number)
            } else {
              this.$message.error(res.message)
            }
          }, err => this.$message.error('服务器异常'))
      }
    },
    addEx() {
      this.dialogFormVisible = true
      this.title = '添加图片'
      this.imageUrl = ''
      this.addForm = {
      }
    },
    editPic(row) {
      this.dialogFormVisible = true
      this.title = '修改图片'
      this.addForm = filterObj(row)
      if (row.img) {
        this.imageUrl = row.img
      }
    },
    delPic(row) {
      let id = row.id
      deleteApi({ ids: id })
        .then(res => {
          if (res.code === '000000') {
            this.$message.success('删除成功')
            this.getIndexPic(this.page.number)
          } else {
            this.$message.error(res.message)
          }
        }, err => this.$message.error('服务器异常'))

    },
    typeFormatter(row) {
      return row.type == 1 ? '图片广告' : '专题广告'
    },
    formatStatus(row, col) {
      return row.state == 1 ? '展示' : "不展示"
    },
    positionFormatter(row) {
      let position = ''
      this.types.some(item => {
        if (row.position === item.value) {
          position = item.title
          return true
        }
      })
      return position
    },
    beforeAvatarUpload(file) {
      return this.upload(file)
    },
    upload(file) {
      this.fullscreenLoading = true
    },
    handleCurrentChange(val) {
      this.getIndexPic(val)
    },
    cancel(addForm) {
      this.dialogFormVisible = false
      this.getIndexPic(this.page.number)
    },
    uploadRequest(file) {
      const fm = new FormData()
      fm.append('fileName', file.file)
      fm.append('fileType', '1')
      uploadFile(fm, res => {
        this.fullscreenLoading = false
        if (res.code === '000000') {
          this.imageUrl = res.result.storageName
        }
      }, err => {
        this.fullscreenLoading = false
      })
    },
    switchChange(row) {
      disableApi({
        id: row.id,
        state: row.state ? '0' : '1'
      }).then(res => {
        if (res.code === '000000') {
          this.$message.success('修改成功')
          this.getIndexPic(this.page.number)
        } else {
          this.$message.error(res.message)
        }
      }, () => {
        this.$message.error('网络错误')
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.handle-box {
  margin-bottom: 1%;
  .search {
    width: 30%;
  }
  //   .expert {
  //   }
}

.block {
  text-align: center;
  margin-top: 1%;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>